package wall

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"strings"
	"time"
)

type BingHpApiModel struct {
	MediaContents []BingHpApiModelContent
}

type BingHpApiModelContent struct {
	ImageContent BingHpApiModelContentImage
}

type BingHpApiModelContentImage struct {
	Image BindHpApiModelContentImageImage
}

type BindHpApiModelContentImageImage struct {
	//Url string
	Wallpaper string
}

func GetBingImageURL(mode string) (imgURL string, imgFilename string) {
	defer SetRandomWall()

	response, err := http.Get("https://cn.bing.com/hp/api/model")
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	resp, _ := ioutil.ReadAll(response.Body)
	var res BingHpApiModel
	err = json.Unmarshal(resp, &res)
	if err != nil {
		panic("BING每日一图解析错误")
	}
	if len(res.MediaContents) == 0 {
		panic("未获取BING每日一图数据")
	}

	if mode == "today" {
		imgURL = res.MediaContents[0].ImageContent.Image.Wallpaper
		if strings.Index(imgURL, "rf=") > 0 {
			imgURL = imgURL[:strings.Index(imgURL, "rf=")-1]
		}
		log.Println("今日Bing桌面URL:" + imgURL)
		imgFilename = imgURL[7:]
		return "https://s.cn.bing.net" + imgURL, imgFilename
	} else {
		rand.Seed(time.Now().Unix())
		randIndex := rand.Intn(len(res.MediaContents))
		imgURL = res.MediaContents[randIndex].ImageContent.Image.Wallpaper
		if strings.Index(imgURL, "rf=") > 0 {
			imgURL = imgURL[:strings.Index(imgURL, "rf=")-1]
		}
		log.Println("今日Bing桌面URL:" + imgURL)
		imgFilename = imgURL[7:]
		return "https://s.cn.bing.net" + imgURL, imgFilename
	}
}
